<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.js"></script>
</head>
<body>
    <div id="app">
        <div v-for="album of albums">
            <h3>专辑名称 ：{{album.title}} 价格：{{album.price}}</h3>
            <table>
                <tr>
                    <th>歌曲名称</th>
                    <th>时间长度</th>
                    <th>操作</th>
                </tr>
                <tr v-for="music of album.musics">
                    <td>{{music.name}}</td>
                    <td>{{music.duration}}</td>
                    <td><button>ddd</button></td>
                </tr>
            </table>
            <button @click="buy(album)">加入购物车</button>
        </div>
        <h3>你的购物车：</h3>
        <ul>
            <li v-for="item of shoppingCart">
                {{item.album.title}}----{{item.album.price}}------{{item.count}}--
                <button @click="item.count++">加</button>
                <button @click="decrement(item)">减</button>
                <button @click="deleteItem(item)">删除</button>
            </li>
        </ul>
        <h3>总价：$ {{totalPrice}}</h3>

    </div>

<script>
    let albums=[
        {title:'新长征路上的摇滚',price:28,musics:[{
                name:'一块红布',duration:120
            },{
                name:'最后一枪',duration:180
            }
            ]},

        {title:'解决',price:76,musics:[{
                name:'解决',duration:170
            },{
                name:'好时光',duration:220
            }
            ]}
    ];

    new Vue({
        el:'#app',
        data:{albums:albums,shoppingCart:[]},
        methods:{
            buy(album){
                let index=this.shoppingCart.findIndex(item=>album.title==item.album.title)
                if(index<0)
                    this.shoppingCart.push({album:Object.assign({},album),count:1})
                else
                    this.shoppingCart[index].count++
            },
            deleteItem(item){
                let index=this.shoppingCart.indexOf(item);
                this.shoppingCart.splice(index,1)
            },
            decrement(item){
                if((--item.count)==0) this.deleteItem(item)
            }

        },
        computed:{
            totalPrice(){
                return this.shoppingCart.reduce((init,item)=>init+item.count*item.album.price,0)
                //return this.shoppingCart.reduce((init,item)=>init)
            }
        }
    })


</script>
</body>
</html>